package com.server;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.db.DB;
import com.tools.Constants;

/**
 * @author lemonjesnme
 * @category add friends
 */
public class C2S1addFriends extends HttpServlet {
	
	@Override
	public void init() throws ServletException {
		Constants.init();
		System.out.println("DB name:"+Constants.DBNAME);
		DB.connDB();
		super.init();
	}
	
	private static final long serialVersionUID = 1L;
	private HashMap<String, String> hm = new HashMap<String, String>();

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		Enumeration<String> er = request.getParameterNames();
		System.out.println("[vswb1] whitebox1 begin");
		PrintWriter writer = response.getWriter();

		String user_id = null;
		String _id = null;
		String value = null;
		String cmd = null;
		while (er.hasMoreElements()) {
			String element = er.nextElement();

			if (element.equals("cmd")) {
				cmd = request.getParameterValues("cmd")[0];
				System.out.println("[vswb1] cmd:" + cmd);
			}
			/**
			 * return the friends table primay id
			 */
			if (element.equals("user_id")) {
				user_id = request.getParameterValues("user_id")[0];
				System.out.println("[vswb1] user_id:" + user_id);
			}

			if (element.equals("_id")) {
				_id = request.getParameterValues("_id")[0];
				System.out.println("[vswb1] _id:" + _id);
			}
			/**
			 * accept the user to add friends from local telephone list, insert
			 * into friends table
			 */
			if (element.equals("selected")) {
				value = request.getParameterValues("selected")[0];
				System.out.println("[vswb1] selected from client:" + value);
			}
		}

		if (cmd.equals("1") && (user_id != null) && (_id != null)) {
			System.out.println("[vswb1] mark _id:"+_id+" user_id:"+ user_id);
			if(user_id.equals(_id)){
				return;
			}
			ResultSet rs = DB.select("Friends", "_id", "user_id", user_id, null);
			try {
				while (rs.next()) {
					String temp = rs.getString("_id");
					if (temp.equals(_id)) {
						return;
					}
				}
				DB.insert("insert into friends(_id,user_id) values('"+_id+"','"+user_id+"');" );
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		if (cmd.equals("2") && (user_id != null) && (_id != null)) {
			System.out.println("[vswb1] delete _id:"+_id+" user_id:"+user_id);
			DB.delete("delete from friends where _id='"+_id+"' and user_id='"+user_id+"';");
		}
	}

}
